const vscode = require('vscode');
const fs = require('fs');
const path = require('path');
const { stopGeneration, sendToQwenStream, resetConversationHistory } = require('../utils/utils.js');
const AIService = require('../src/agent/aiService.js');
const AgentTask = require('./agent/agentTask');
const FileCreator = require('./agent/fileCreator');
const AgentManager = require('./agent/agentManager');
const { parseMentions, searchWorkspaceFiles } = require('./context/ContextMentions');

// 创建AI服务实例
const aiService = new AIService();

class ChatViewProvider {
    constructor(context) {
        this.context = context;
        this._view = undefined;
        this.visibilityState = 'visible';
        this.agentTask = null;
        this.fileCreator = null;
        this.agentManager = null;
        this._webviewState = null;  // 添加状态存储
        this.currentReplyBlock = null; // 添加回复块变量
        this._agentsInitialized = false; // 添加初始化标志，避免重复初始化
        this._webviewInitialized = false; // 添加WebView初始化标记
        this._cachedHtml = null; // 缓存HTML内容
        this._agentInitPromise = null; // 添加初始化Promise
        this.mcpService = null; // 添加MCP服务字段
        
        // 立即开始初始化代理（但不等待完成）
        this._agentInitPromise = this.initializeAgents();
        
        // 注册resetFileChanges命令
        this.context.subscriptions.push(
            vscode.commands.registerCommand('xinye.resetFileChanges', () => {
                this.resetFileChanges();
            })
        );
        
        // 尝试获取MCP服务
        try {
            if (global.getMcpService) {
                this.mcpService = global.getMcpService();
            }
        } catch (error) {
            console.error('获取MCP服务失败:', error);
        }
    }

    async initializeAgents() {
        // 如果已初始化，直接返回
        if (this._agentsInitialized) return;
        
        const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
        if (workspaceRoot) {
            try {
                this.agentTask = await new AgentTask().initialize();
                this.fileCreator = await new FileCreator(workspaceRoot).initialize();
                this.agentManager = await new AgentManager().initialize(this.context);
                this._agentsInitialized = true; // 设置标志位
                console.log('Agents初始化成功');
            } catch (error) {
                console.error('Agents初始化失败:', error);
                throw error; // 抛出错误以便调用者知道初始化失败
            }
        } else {
            throw new Error('工作区不存在，无法初始化代理');
        }
    }

    resolveWebviewView(webviewView) {
        this._view = webviewView;
        webviewView.webview.options = {
            enableScripts: true,
            retainContextWhenHidden: true,
            localResourceRoots: [
                vscode.Uri.joinPath(this.context.extensionUri, 'image'),
                vscode.Uri.joinPath(this.context.extensionUri, 'HomePage')
            ]
        };

        const userIconPath = webviewView.webview.asWebviewUri(
            vscode.Uri.joinPath(this.context.extensionUri, 'image', '1.jpg')
        );
        const botIconPath = webviewView.webview.asWebviewUri(
            vscode.Uri.joinPath(this.context.extensionUri, 'image', '2.jpg')
        );

        // 仅在首次加载或缓存失效时生成HTML，添加优化标记
        if (!this._cachedHtml) {
            const htmlPath = path.join(this.context.extensionPath, 'HomePage', 'chat.html');
            let html = fs.readFileSync(htmlPath, 'utf8');
            
            // 添加优化标记，防止不必要的重新初始化
            html = html.replace('<head>', '<head>\n<meta name="vscode-webview-cache" content="no-revalidate">');
            
            // 添加预加载指令
            html = html.replace('<head>', '<head>\n<link rel="preload" href="*" as="script">');
            
            // 重要：确保使用真实的WebView URI替换头像路径
            html = html.replace(/USER_AVATAR_PATH/g, userIconPath);
            html = html.replace(/BOT_AVATAR_PATH/g, botIconPath);
            
            this._cachedHtml = html;
        } else {
            // 即使使用缓存的HTML，也需要确保每次都更新头像路径
            this._cachedHtml = this._cachedHtml.replace(/USER_AVATAR_PATH/g, userIconPath);
            this._cachedHtml = this._cachedHtml.replace(/BOT_AVATAR_PATH/g, botIconPath);
        }

        // 无论何时都立即设置HTML内容，确保视图立即可见
        webviewView.webview.html = this._cachedHtml;

        // 向WebView注入一个标记以避免重复初始化
        webviewView.webview.onDidReceiveMessage(
            async message => {
                // 第一次收到消息时，设置已初始化标记
                if (!this._webviewInitialized && message.command !== 'saveState') {
                    this._webviewInitialized = true;
                    console.log('WebView已完成初始化');
                }
                
                switch (message.command) {
                    case 'saveState':
                        // 保存webview状态
                        this._webviewState = message.state;
                        break;
                    case 'sendMessage':
                        try {
                            // 获取对话模式
                            const mode = message.mode || 'normal';
                            
                            // 处理@提及内容（对普通模式和代理模式都要处理）
                            let processedText = message.text;
                            if (message.text && message.text.includes('@')) {
                                try {
                                    processedText = await parseMentions(message.text);
                                    console.log('处理@提及完成:', processedText.substring(0, 100) + '...');
                                } catch (error) {
                                    console.error('处理@提及出错:', error);
                                }
                            }
                            
                            // 更新消息文本
                            const processedMessage = { ...message, text: processedText };
                            
                            if (mode === 'agent') {
                                // 代理模式下的处理
                                await this.handleAgentMode(processedMessage, webviewView.webview);
                            } else {
                                // 普通对话模式
                                await sendToQwenStream(processedMessage, webviewView.webview);
                            }
                        } catch (error) {
                            vscode.window.showErrorMessage('通信失败：' + error.message);
                            webviewView.webview.postMessage({
                                command: 'receiveError',
                                error: '通信失败：' + error.message
                            });
                        }
                        break;
                    case 'stopGeneration':
                        if (this.agentTask) {
                            this.agentTask.stopCurrentTask();
                        }
                        stopGeneration();
                        break;
                    case 'clearContext':
                        // 处理清除上下文命令
                        try {
                            if (this.agentTask) {
                                // 清除代理模式下的上下文历史
                                this.agentTask.clearConversationHistory();
                                
                                // 重置代理工具的待确认变更
                                if (this.agentTask.tools) {
                                    this.agentTask.tools.resetPendingChanges();
                                }
                            }
                            
                            // 也清除普通模式的历史，无论当前是什么模式
                            if (typeof resetConversationHistory === 'function') {
                                resetConversationHistory();
                            }
                            
                            // 通知前端上下文已清除
                            webviewView.webview.postMessage({
                                command: 'progressUpdate',
                                type: 'system',
                                message: 'AI助手上下文历史已清除'
                            });
                            
                            // 通知前端重置文件变更
                            this.resetFileChanges();
                        } catch (error) {
                            console.error('清除上下文失败:', error);
                            webviewView.webview.postMessage({
                                command: 'progressUpdate',
                                type: 'error',
                                message: '清除上下文失败: ' + error.message
                            });
                        }
                        break;
                    case 'createFile':
                        if (this.fileCreator) {
                            try {
                                const result = await this.fileCreator.createFile(
                                    message.fileName,
                                    message.content,
                                    message.targetDir
                                );
                                webviewView.webview.postMessage({
                                    command: 'fileCreated',
                                    success: result.success,
                                    path: result.relativePath,
                                    error: result.error
                                });
                            } catch (error) {
                                webviewView.webview.postMessage({
                                    command: 'fileCreated',
                                    success: false,
                                    error: error.message
                                });
                            }
                        }
                        break;
                    case 'executeCommand':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                const result = await this.agentTask.tools.executeCommand(
                                    message.command,
                                );
                                webviewView.webview.postMessage({
                                    command: 'commandExecuted',
                                    success: result.success,
                                    output: result.stdout,
                                    error: result.error || result.stderr
                                });
                            } catch (error) {
                                webviewView.webview.postMessage({
                                    command: 'commandExecuted',
                                    success: false,
                                    error: error.message
                                });
                            }
                        }
                        break;
                    case 'approveToolAction':
                        if (this.agentTask) {
                            // 用户批准了工具操作，需要继续处理
                            try {
                                const result = await this.agentTask.handleToolApproval(
                                    message.toolId,
                                    true,
                                    message.additionalInput
                                );
                                webviewView.webview.postMessage({
                                    command: 'toolActionResult',
                                    success: result.success,
                                    toolId: message.toolId,
                                    result: result
                                });
                            } catch (error) {
                                webviewView.webview.postMessage({
                                    command: 'toolActionResult',
                                    success: false,
                                    toolId: message.toolId,
                                    error: error.message
                                });
                            }
                        }
                        break;
                    case 'rejectToolAction':
                        if (this.agentTask) {
                            // 用户拒绝了工具操作，需要继续处理
                            try {
                                const result = await this.agentTask.handleToolApproval(
                                    message.toolId,
                                    false,
                                    message.feedback
                                );
                                webviewView.webview.postMessage({
                                    command: 'toolActionResult',
                                    success: false, // 工具被拒绝
                                    toolId: message.toolId,
                                    result: result
                                });
                            } catch (error) {
                                webviewView.webview.postMessage({
                                    command: 'toolActionResult',
                                    success: false,
                                    toolId: message.toolId,
                                    error: error.message
                                });
                            }
                        }
                        break;
                    case 'userApproval':
                        if (this.agentTask) {
                            console.log("收到用户操作响应", {
                                approved: message.approved,
                                feedback: message.feedback,
                                selectedOption: message.selectedOption
                            });
                            await this.agentTask.handleUserApproval(message.approved, message.feedback || '', message.selectedOption);
                        }
                        break;
                    case 'mcpApproval':
                        // 处理MCP工具批准/拒绝
                        if (this.agentTask) {
                            console.log("收到MCP操作响应", {
                                approved: message.approved,
                                feedback: message.feedback
                            });
                            await this.agentTask.handleUserApproval(message.approved, message.feedback || '', null);
                        }
                        break;
                    case 'searchFiles':
                        // 处理文件搜索请求
                        try {
                            const query = message.query;
                            const results = await searchWorkspaceFiles(query);
                            webviewView.webview.postMessage({
                                command: 'searchFilesResult',
                                results: results
                            });
                        } catch (error) {
                            console.error('文件搜索失败:', error);
                            webviewView.webview.postMessage({
                                command: 'searchFilesResult',
                                results: []
                            });
                        }
                        break;
                    case 'showOptions':
                        // 确保options是数组类型
                        let optionsArray = message.options;
                        if (!Array.isArray(optionsArray)) {
                            if (typeof optionsArray === 'string') {
                                // 尝试将逗号分隔的字符串转换为数组
                                optionsArray = optionsArray.split(',').map(opt => opt.trim());
                            } else {
                                // 如果无法处理，则创建一个默认选项数组
                                optionsArray = ["选项1", "选项2", "选项3"];
                                console.error("选项格式错误，使用默认选项", message.options);
                            }
                        }
                        
                        webviewView.webview.postMessage({
                            command: 'showOptions',
                            message: message.message || '请选择一个选项',
                            options: optionsArray
                        });
                        break;
                    // 添加文件变更相关消息处理
                    case 'acceptChange':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                // 确认变更
                                await this.agentTask.tools.confirmChange(message.filePath);
                            } catch (error) {
                                console.error('确认变更失败:', error);
                            }
                        }
                        break;
                    case 'rejectChange':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                // 拒绝变更
                                await this.agentTask.tools.rejectChange(message.filePath);
                            } catch (error) {
                                console.error('拒绝变更失败:', error);
                            }
                        }
                        break;
                    case 'acceptAllChanges':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                // 确认所有变更
                                for (const [filePath] of this.agentTask.tools.pendingChanges) {
                                    await this.agentTask.tools.confirmChange(filePath);
                                }
                            } catch (error) {
                                console.error('确认所有变更失败:', error);
                            }
                        }
                        break;
                    case 'rejectAllChanges':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                // 拒绝所有变更
                                for (const [filePath] of this.agentTask.tools.pendingChanges) {
                                    await this.agentTask.tools.rejectChange(filePath);
                                }
                            } catch (error) {
                                console.error('拒绝所有变更失败:', error);
                            }
                        }
                        break;
                    case 'openDiffView':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                // 获取待确认的变更
                                const change = this.agentTask.tools.pendingChanges.get(message.filePath);
                                if (change) {
                                    // 显示差异视图
                                    await this.agentTask.tools.showDiffView(
                                        message.filePath,
                                        change.originalContent,
                                        change.newContent
                                    );
                                }
                            } catch (error) {
                                console.error('打开差异视图失败:', error);
                            }
                        }
                        break;
                    case 'openFile':
                        if (this.agentTask && this.agentTask.tools) {
                            try {
                                // 打开文件
                                const workspaceRoot = vscode.workspace.workspaceFolders?.[0]?.uri.fsPath;
                                if (workspaceRoot) {
                                    const fullPath = path.join(workspaceRoot, message.filePath);
                                    const uri = vscode.Uri.file(fullPath);
                                    vscode.window.showTextDocument(uri);
                                }
                            } catch (error) {
                                console.error('打开文件失败:', error);
                            }
                        }
                        break;
                    case 'showInformation':
                        if (message.message) {
                            vscode.window.showInformationMessage(message.message);
                        }
                        break;
                    case 'getMcpServers':
                    case 'addServer':
                    case 'deleteServer':
                    case 'toggleServer':
                    case 'getServerTools':
                    case 'toggleToolAutoApprove':
                    case 'openMcpSettings':
                        await this.handleMcpMessage(message);
                        break;
                }
            }
        );
    }

    async handleAgentMode(message, webview) {
        // agent模式已经在前面的代码中处理了@提及，这里只需继续处理
        try {
            // 继续现有的代理模式处理
            if (!this._agentsInitialized) {
                webview.postMessage({
                    command: 'progressUpdate',
                    type: 'system',
                    message: '正在初始化代理模式...'
                });
                
                try {
                    await this._agentInitPromise; // 等待初始化完成
                } catch (error) {
                    webview.postMessage({
                        command: 'progressUpdate',
                        type: 'error',
                        message: '代理模式初始化失败: ' + error.message
                    });
                    return;
                }
            }
            
            // 恢复历史消息以重新创建会话上下文
            const historyMessages = this._webviewState?.messages || [];
            
            // 处理代理任务执行
            await this.executeAgentTask(message, webview, this.createProgressCallback(webview), historyMessages);
        } catch (error) {
            console.error('代理模式处理失败:', error);
            webview.postMessage({
                command: 'agentError',
                error: error.message
            });
        }
    }

    // 创建进度回调函数
    createProgressCallback(webview) {
        return (progressInfo) => {
            if (!progressInfo) return;
            
            switch(progressInfo.type) {
                case 'ai':

                        webview.postMessage({
                            command: 'receiveMessage',
                            text: progressInfo.message || ''
                        });
                    break;
                case 'thinking':
                    // 处理思考过程内容
                    webview.postMessage({
                        command: 'receiveThinking',
                        text: progressInfo.message || ''
                    });
                    break;

                case 'system':
                case 'success':
                case 'warning':
                case 'error':
                    // 处理系统消息和状态更新
                    webview.postMessage({
                        command: 'progressUpdate',
                        type: progressInfo.type,
                        message: progressInfo.message
                    });
                    break;
                case 'tool_approval':
                    // 处理需要用户批准的工具调用
                    // 将工具调用信息拼接到当前回复块
                    if (this.currentReplyBlock !== null) {
                        // 可以选择在这里将工具调用信息添加到回复块
                        this.currentReplyBlock += `\n\n[需要批准: ${progressInfo.toolName}]`;
                        // 更新消息内容
                        webview.postMessage({
                            command: 'receiveMessage',
                            text: this.currentReplyBlock
                        });
                    }
                    // 同时发送工具审批请求
                    webview.postMessage({
                        command: 'requestToolApproval',
                        toolId: progressInfo.toolId,
                        toolName: progressInfo.toolName,
                        toolParams: progressInfo.toolParams,
                        description: progressInfo.description
                    });
                    break;
                case 'tool_result':
                    // 同时发送工具结果信息
                    webview.postMessage({
                        command: 'toolResult',
                        toolId: progressInfo.toolId,
                        success: progressInfo.success,
                        result: progressInfo.result
                    });
                    break;
                case 'userApproval':
                    console.log("向前端发送userApproval请求", {
                        toolName: progressInfo.toolName,
                        params: progressInfo.params,
                        path: progressInfo.path
                    });
                    webview.postMessage({
                        command: 'userApproval',
                        toolName: progressInfo.toolName,
                        params: progressInfo.params,
                        path: progressInfo.path
                    });
                    break;
                case 'mcpToolApproval':
                    console.log("向前端发送mcpToolApproval请求", {
                        toolName: progressInfo.toolName,
                        serverName: progressInfo.serverName,
                        params: progressInfo.params
                    });
                    webview.postMessage({
                        command: 'mcpToolApproval',
                        toolName: progressInfo.toolName,
                        serverName: progressInfo.serverName,
                        params: progressInfo.params
                    });
                    break;
                case 'mcpToolResult':
                    console.log("向前端发送mcpToolResult", {
                        serverName: progressInfo.serverName,
                        toolName: progressInfo.toolName,
                        success: progressInfo.success,
                        result: progressInfo.result,
                        error: progressInfo.error
                    });
                    webview.postMessage({
                        command: 'mcpToolResult',
                        serverName: progressInfo.serverName,
                        toolName: progressInfo.toolName,
                        success: progressInfo.success,
                        result: progressInfo.result,
                        error: progressInfo.error
                    });
                    break;
                case 'thinking_end':
                    // 处理思考结束标记
                    webview.postMessage({
                        command: 'thinkingEnd',
                        message: progressInfo.message
                    });
                    break;
                case 'showOptions':
                    // 确保options是数组类型
                    let optionsArray = progressInfo.options;
                    if (!Array.isArray(optionsArray)) {
                        if (typeof optionsArray === 'string') {
                            // 尝试将逗号分隔的字符串转换为数组
                            optionsArray = optionsArray.split(',').map(opt => opt.trim());
                        } else {
                            // 如果无法处理，则创建一个默认选项数组
                            optionsArray = ["选项1", "选项2", "选项3"];
                            console.error("选项格式错误，使用默认选项", progressInfo.options);
                        }
                    }
                    
                    webview.postMessage({
                        command: 'showOptions',
                        message: progressInfo.message || '请选择一个选项',
                        options: optionsArray
                    });
                    break;
            }
        };
    }

    async executeAgentTask(message, webview, progressCallback, historyMessages = []) {
        try {
            // 保存用户选择的模型信息
            this.agentTask.selectedModel = message.model || "qwen-plus";
            this.agentTask.enableReasoning = message.enableReasoning || false;
            console.log("模型信息：",this.agentTask.selectedModel,this.agentTask.enableReasoning);
            
            // 启动新的Agent任务，传入历史消息
            this.agentTask.startTask(message.text, (progressInfo) => {
                // 使用标准化的消息处理逻辑
                progressCallback(progressInfo);
            }, historyMessages).then(result => {
                // 任务完成，告知前端
                webview.postMessage({
                    command: 'endMessage'
                });
                
                if (!result.success) {
                    webview.postMessage({
                        command: 'agentError',
                        error: result.error
                    });
                } else {
                    // 成功完成任务，发送完成消息
                    progressCallback({
                        type: 'success',
                        message: '任务已完成'
                    });
                    
                    // 不再保存Agent消息到WebView状态
                    // this.saveAgentMessages(webview);
                }
                
                // 任务结束，重置回复块
                this.currentReplyBlock = null;
                
            }).catch(error => {
                // 确保发送结束消息
                webview.postMessage({
                    command: 'endMessage'
                });
                
                webview.postMessage({
                    command: 'agentError',
                    error: error.message
                });
                
                // 错误发生，重置回复块
                this.currentReplyBlock = null;
            });
        } catch (error) {
            webview.postMessage({
                command: 'agentError',
                error: error.message
            });
            
            webview.postMessage({
                command: 'endMessage'
            });
            
            // 错误发生，重置回复块
            this.currentReplyBlock = null;
        }
    }

    /**
     * 保存Agent模式的消息到WebView状态，使聊天历史在会话间保持
     * @param {vscode.Webview} webview - WebView实例
     */
    saveAgentMessages(webview) {
        if (!this.agentTask) return;
        
        try {
            // 获取格式化的消息
            const agentMessages = this.agentTask.getFormattedMessages();
            
            if (agentMessages && agentMessages.length > 0) {
                // 合并现有状态与新消息
                let currentState = this._webviewState || { messages: [] };
                
                // 确保messages存在
                if (!currentState.messages) {
                    currentState.messages = [];
                }
                
                // 避免重复添加用户消息的问题
                // 1. 检查当前状态中是否已经有用户的查询消息
                const userQuery = agentMessages.find(msg => msg.sender === 'user');
                const existingUserMsg = currentState.messages.find(msg => 
                    msg.sender === 'user' && userQuery && msg.text === userQuery.text
                );
                
                // 2. 过滤掉已经存在的用户消息
                const uniqueMessages = existingUserMsg ? 
                    agentMessages.filter(msg => msg.sender !== 'user' || msg.text !== userQuery.text) : 
                    agentMessages;
                
                // 3. 过滤掉工具结果消息 (工具结果不应该显示为消息)
                const filteredMessages = uniqueMessages.filter(msg => 
                    !(msg.text && msg.text.startsWith('{"tool":'))
                );
                
                // 如果过滤后仍有消息要添加
                if (filteredMessages.length > 0) {
                    // 合并消息：将过滤后的消息添加到现有消息列表
                    currentState.messages = [...currentState.messages, ...filteredMessages];
                    
                    // 更新存储的状态
                    this._webviewState = currentState;
                    
                    // 通知WebView更新状态
                    webview.postMessage({
                        command: 'restoreState',
                        state: this._webviewState
                    });
                }
            }
        } catch (error) {
            console.error('保存Agent消息失败:', error);
        }
    }

   

    show() {
        if (this._view) {
            this._view.show(true);
        }
    }

    // 添加预热方法，可以在插件激活时调用
    warmup() {
        // 执行预热
        if (this.agentTask) {
            // 尝试执行一个简单操作，初始化模型
            console.log('正在预热AI模型...');
            
            // 禁用进度回调，避免显示预热消息
            const dummyCallback = () => {};
            
            // 执行一个简单任务，加载模型
            this.agentTask.startTask(
                "预热初始化", 
                dummyCallback, 
                [], 
                { enableReasoning: false }
            ).catch(error => {
                console.error('模型预热失败:', error);
            });
        }
    }

    // 通知文件变更
    notifyFileChange(filePath, operation, changeInfo) {
        if (this._view) {
            // 确保changeInfo存在且有正确的格式
            const formattedChangeInfo = changeInfo || {
                added: 0,
                removed: 0
            };
            
            console.log(`发送文件变更通知: ${filePath}, 操作: ${operation}, 行数变化:`, formattedChangeInfo);
            
            this._view.webview.postMessage({
                command: 'fileChanged',
                filePath,
                operation,
                changeInfo: formattedChangeInfo
            });
        }
    }

    // 通知变更确认
    notifyFileChangeConfirmed(filePath, operation) {
        if (this._view) {
            this._view.webview.postMessage({
                command: 'fileChangeConfirmed',
                filePath,
                operation
            });
        }
    }

    // 通知变更拒绝
    notifyFileChangeRejected(filePath) {
        if (this._view) {
            this._view.webview.postMessage({
                command: 'fileChangeRejected',
                filePath
            });
        }
    }

    // 通知前端重置文件变更
    resetFileChanges() {
        if (this._view) {
            this._view.webview.postMessage({
                command: 'resetFileChanges'
            });
        }
    }

    // 设置MCP服务实例
    setMcpService(service) {
        this.mcpService = service;
        // 如果WebView已初始化，通知WebView更新MCP状态
        if (this._view && this._webviewInitialized) {
            this.updateMcpServers();
        }
    }

    // 显示MCP管理界面
    showMcpManager() {
        if (!this._view) return;
        
        this._view.webview.postMessage({
            command: 'action',
            action: 'showMcpManager'
        });
        
        // 请求更新MCP服务器列表
        this.updateMcpServers();
    }

    // 显示聊天界面
    showChatView() {
        if (!this._view) return;
        
        this._view.webview.postMessage({
            command: 'action',
            action: 'showChatView'
        });
    }

    // 更新MCP服务器列表
    async updateMcpServers() {
        if (!this._view || !this.mcpService) return;
        
            try {
            const servers = await this.mcpService.getServers();
            console.log('更新MCP服务器列表 (所有):', servers);
            // 发送新格式消息，确保包含 status 和 disabled 状态
            this._view.webview.postMessage({
                command: 'mcpServersUpdated',
                servers: servers.map(server => ({
                    name: server.name,
                    status: server.status || 'disconnected', // 提供默认状态
                    disabled: server.disabled === true, // 确保是布尔值
                    error: server.error || ''
                    // 不在此处发送工具列表，工具列表在选择服务器后单独获取
                }))
            });
            } catch (error) {
            console.error('获取MCP服务器列表失败:', error);
            }
        }
        
    // 处理MCP相关消息
    async handleMcpMessage(message) {
        if (!this.mcpService) {
            console.error('MCP服务未初始化');
            return;
        }
        
        try {
            switch (message.command) {
                case 'getMcpServers':
                    await this.updateMcpServers();
                    break;
                    
                case 'addServer':
                    if (message.serverConfig) {
                        await this.mcpService.addServer(message.serverConfig);
                        await this.updateMcpServers();
                    }
                    break;
                    
                case 'deleteServer':
                    if (message.serverName) {
                        // Show confirmation dialog first
                        const result = await vscode.window.showWarningMessage(
                            `确定要删除MCP服务器 "${message.serverName}" 吗? 这将从配置文件中移除它。`,
                            { modal: true }, // Makes the dialog blocking
                            '删除',        // Action item 1
                            '取消'         // Action item 2
                        );
            
                        if (result === '删除') {
                            // User confirmed deletion
                            try {
                                await this.mcpService.deleteServer(message.serverName); // Ensure correct method name
                        await this.updateMcpServers();
                                vscode.window.showInformationMessage(`已删除服务器: ${message.serverName}`);
                            } catch (error) {
                                console.error(`删除服务器失败: ${message.serverName}`, error);
                                vscode.window.showErrorMessage(`删除服务器失败: ${error.message}`);
                            }
                        } else {
                            // User cancelled
                            console.log(`删除服务器 ${message.serverName} 已取消`);
                        }
                    }
                    break;
                    
                case 'toggleServer':
                    if (this.mcpService && message.serverName) {
                        console.log(`切换服务器 ${message.serverName} 状态为 ${message.enable ? '启用' : '禁用'}`);
                        await this.mcpService.toggleServer(message.serverName, message.enable)
                            .then(() => {
                                // 服务器状态更新后，刷新服务器列表
                                this.updateMcpServers();
                            })
                            .catch(err => {
                                console.error(`切换服务器 ${message.serverName} 状态失败`, err);
                                vscode.window.showErrorMessage(`无法${message.enable ? '启用' : '禁用'}服务器 ${message.serverName}: ${err.message}`);
                            });
                    }
                    break;
                    
                case 'getServerTools':
                    if (message.serverName) {
                        try {
                            // 获取服务器工具
                        const tools = await this.mcpService.getServerTools(message.serverName);
                            
                            // 发送工具数据到WebView
                            if (this._view) {
            this._view.webview.postMessage({
                                command: 'serverToolsData',
                                serverName: message.serverName,
                                tools: tools // 发送包含autoApprove状态的完整工具信息
                            });
                            }
                        } catch (error) {
                            console.error(`获取服务器 ${message.serverName} 工具失败:`, error);
                            if (this._view) {
                                this._view.webview.postMessage({
                                    command: 'mcpError',
                                    error: `获取工具失败: ${error.message}`
                                });
                            }
                        }
                    }
                    break;
                    
                case 'toggleToolAutoApprove':
                    if (this.mcpService && message.serverName && message.toolNames) {
                        try {
                            console.log(`切换自动批准: ${message.serverName}, 工具: ${message.toolNames}, 状态: ${message.autoApprove}`);
                            await this.mcpService.toggleToolAutoApprove(message.serverName, message.toolNames, message.autoApprove);
                            // 刷新工具列表
                            await this.handleMcpMessage({
                                command: 'getServerTools',
                                serverName: message.serverName
                            });
                        } catch (error) {
                            console.error('切换工具自动批准失败:', error);
                            // 检查 this._view 是否存在
                            if (this._view && this._view.webview) {
                                this._view.webview.postMessage({
                                    command: 'mcpError',
                                    error: `切换自动批准失败: ${error.message}`
                                });
                            } else {
                                vscode.window.showErrorMessage(`切换自动批准失败: ${error.message}`);
                            }
                        }
                    } else {
                        console.warn('缺少必要参数无法切换自动批准状态', message);
                    }
                    break;
                case 'openMcpSettings':
                    if (message.action === 'openFile') {
                        // 打开MCP配置文件
                        try {
                            const settingsPath = await this.mcpService.getMcpSettingsFilePath();
                            console.log('打开MCP配置文件路径:', settingsPath);
                            const uri = vscode.Uri.file(settingsPath);
                            await vscode.window.showTextDocument(uri);
                        } catch (error) {
                            console.error('打开MCP配置文件失败:', error);
                            vscode.window.showErrorMessage(`打开MCP配置文件失败: ${error.message}`);
                        }
                    } else {
                        // 打开设置界面
                    await vscode.commands.executeCommand('workbench.action.openSettings', 'mcp');
                    }
                    break;
                case 'showInformation':
                    if (message.message) {
                        vscode.window.showInformationMessage(message.message);
                    }
                    break;
            }
        } catch (error) {
            console.error('处理MCP消息失败:', error);
            if (this._view) {
                this._view.webview.postMessage({
                    command: 'mcpError',
                    error: error.message
                });
            }
        }
    }
}

module.exports = ChatViewProvider;